<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!--卡片 -->
    <el-card>
      <!-- 搜索和添加用户 -->
      <el-row :gutter="20">
        <!-- 表单输入框 -->
        <el-col :span="6">
          <el-input
            placeholder="请输入内容"
            v-model="UsersInfo.query"
            clearable
            @input="NullSearch($event)"
          >
            <el-button slot="append" icon="el-icon-search" @click=" getUsers"></el-button>
          </el-input>
        </el-col>
        <!-- 添加用户 -->
        <el-col :span="4">
          <el-Button type="primary" @click="dialogVisible = true">添加用户</el-Button>
        </el-col>
      </el-row>

      <!-- 用户表格 -->
      <el-table :data="UsersList" style="width: 100%" stripe border>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column label="用户当前状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)"></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="showRoleDialog(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="UsersInfo.pagenum"
        :page-sizes="[1, 2, 4, 6]"
        :page-size="UsersInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalUsers"
      ></el-pagination>
    </el-card>

    <!-- 添加用户对话框  -->
    <el-dialog title="提示" :visible.sync=" dialogVisible" width="50%" @close="addFormClose">
      <!--内容主题区域 -->
      <el-form ref="addFormRef" :model="addForm" label-width="80px" :rules="addFormRules">
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary"  @click="adduser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户的对话框 -->
    <el-dialog title="提示" :visible.sync=" editdialogVisible" width="50%" @close = "editDialogClosed">
      <!-- 内容区 -->
      <el-form :model="editform" :rules="editformRules" ref="editformRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editform.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editform.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editform.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
     <span slot="footer" class="dialog-footer">
       <el-button @click=" editdialogVisible = false">取 消</el-button>
       <el-button type="primary" @click="editUserInfo">确 定</el-button>
     </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="50%">
      <div>
        <p>用户名称: {{ setRoleUsers.username }}</p>
        <p>用户名称: {{ setRoleUsers.role_name }}</p>
        <!-- 角色列表的下拉选项  -->
        <p>
          角色列表:
          <el-select v-model="setRoleID" placeholder="请选择">
            <el-option
              v-for="item in RolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span  slot="footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    //  验证邮箱的规则
    var checkEmail = (rule, value, callback) => {
      // 验证邮箱的正则表达式
      const regEmail = /^[a-zA-Z0-9_-]+@([a-zA-Z0-0_-])+(\.[a-zA-Z0-0_-])+/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的邮箱'))
    }

    // 验证手机号的规则
    var checkMobile = (rule, value, callback) => {
      // 验证邮箱的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的手机号'))
    }

    return {
      // 获取Users列表的参数对象
      UsersInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      // 保存用户列表
      UsersList: [],
      // 保存每页的totalUsers用户数量
      totalUsers: 0,
      // 添加用户是否显示
      dialogVisible: false,
      // 添加用户表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加表单数据的验证
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 编辑修改用户对话框的显示与否
      editdialogVisible: false,
      // 存放查询到的用户信息
      editform: {},
      // 修改表单的验证规则对象
      editformRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 分配角色对话框
      setRoleDialogVisible: false,
      // 要分配角色的用户
      setRoleUsers: {},
      // 要添加角色的ID值
      setRoleID: '',
      // 角色列表数据
      RolesList: []
    }
  },
  created() {
    // 调用获取用户数据的函数
    this.getUsers()
  },
  methods: {
    // 获取用户
    getUsers() {
      this.$http.get('users', { params: this.UsersInfo }).then((res) => {
        if (res.data.meta.status !== 200) {
          this.$message.error('获取用户列表失败')
        } else {
          this.UsersList = res.data.data.users
          this.totalUsers = res.data.data.total
          console.log(this.totalUsers)
        }
      })
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      console.log(newSize)
      this.UsersInfo.pagesize = newSize
      this.getUsers()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.UsersInfo.pagenum = newPage
      this.getUsers()
    },
    userStateChanged(userinfo) {
      console.log(userinfo)
      this.$http
        .put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
        .then((res) => {
          if (res.data.status === 200) {
            return this.$message.error('修改失败')
          }
          return this.$message.success('更新状态成功')
        })
    },
    // 搜索框为空时 自动搜索
    NullSearch(e) {
      if (e === '') {
        this.getUsers()
      }
    },
    // 对话框关闭 清空输入框
    addFormClose() {
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户
    adduser() {
      this.$refs.addFormRef.validate(valid => {
        if (!valid) return this.$message.error(' 请输入正确的格式 ')

        this.$http.post('users', this.addForm).then(res => {
          if (res.data.meta.status !== 201) {
            return this.$message.error('添加用户失败')
          } else {
            this.$message.success('添加用户成功')
            this.dialogVisible = false
            this.getUsers()
          }
        })
      })
    },
    // 展示编辑用户的对话框
    showEditDialog(id) {
      this.editdialogVisible = true
      console.log(id)
      this.$http.get(`users/${id}`).then(res => {
        const { data } = res
        if (data.meta.status !== 200) return this.$message.error('查询用户信息失败')
        this.editform = data.data
      })
    },
    // 监听修改用户对话框的关闭事件
    editDialogClosed() {
      this.$refs.editformRef.resetFields()
      // 对表单进行数据预验证
    },
    // 修改用户并提交
    editUserInfo() {
      // 进行预验证
      this.$refs.editformRef.validate(valid => {
        if (!valid) return this.$message.error('修改数据格式不正确')
        // 发起修改1用户的数据请求
        this.$http.put(`users/${this.editform.id}`, this.editform).then(res => {
          const { data } = res
          if (data.meta.status !== 200) return this.$message.error('更新用户信息失败')
          // 更新用户信息成功
          this.$message.success('更新用户数据成功')
          // 重新获取列表数据
          this.getUsers()
          // 关闭对话框
          this.editdialogVisible = false
        })
      })
    },
    // 根据id删除对应的用户信息
    async removeUserById(id) {
      // 弹框询问是否删除数据
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      // 删除用户
      this.$http.delete(`users/${id}`).then(res => {
        console.log(res)
        const { data } = res
        if (data.meta.status !== 200) return this.$message.error('删除用户失败')
        this.$message.success('删除用户成功')
        this.getUsers()
      })
    },
    // 显示分配角色对话框
    async showRoleDialog(role) {
      this.setRoleDialogVisible = true
      // 保存要分配角色的用户ID
      this.setRoleUsers = role
      // 获取角色列表数据
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.RolesList = res.data
      console.log(this.RolesList)
    },
    // 点击按钮。分配角色
    async setRole() {
      // 判断是否选择了角色
      if (!this.setRoleID) return this.$message.error('请选择角色')
      // 根据ID值和该用户的ID进行分配角色
      const { data: res } = await this.$http.put(`users/${this.setRoleUsers.id}/role`, { rid: this.setRoleID })
      if (res.meta.status !== 200) return this.$message.error('分配角色失败')
      this.$message.success('分配角色成功')
      this.setRoleDialogVisible = false
      this.setRoleUsers = {}
      this.setRoleID = 0
      this.getUsers()
    }
  }
}
</script>

<style lang="less">
.el-breadcrumb {
  margin-bottom: 20px;
}
.el-table {
  margin-top: 20px;
}
.el-pagination {
  margin-top: 15px;
}
</style>
